﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Web.Script.Serialization;

namespace ScottCateAjax2008.Lesson02
{
    public enum Noun
    {
        Person,
        Place,
        Thing
    }

    public class D_NounEnumConverter : JavaScriptConverter
	{
        [ConfigurationProperty("maxJsonLength", DefaultValue = 1024)]
        public int MaxJsonLength { get; set; }
		public override IEnumerable<Type> SupportedTypes
		{
	        get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(Noun) })); }		
       	}

		public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
		{
			var result = new Dictionary<string, object>();
            if (obj.GetType() == typeof(Noun))
			{
                result["Nouns"] = string.Format("{0}: {1}", ((long)((Noun)obj)), obj);
			}

			return result;
		}

		public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
		{
			if (dictionary == null)
				throw new ArgumentNullException("dictionary");

			if (dictionary.ContainsKey("Nouns"))
			{				// Deserialize the privilege.
				long ret;
				if (long.TryParse((string)dictionary["Nouns"], out ret))
					return (Noun)ret;
			}
			return null;
		}

	}
}
